package art.server.servlets;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import art.server.db.DatabaseHandler;
import art.server.db.entities.Art;

public class ArtDownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String artId = req.getParameter("artId");
		Art art = DatabaseHandler.getInstance().getArt(Long.parseLong(artId));
		String[] temps = art.getFileName().split("\\.");
		String fileExt = temps[temps.length-1];
		if (fileExt.equals("jpg")) {
			resp.setContentType("image/jpeg");
			//resp.setContentLength(art.getFile().length);
		} else if (fileExt.equals("png")) {
			resp.setContentType("image/png");
		} else if (fileExt.equals("txt")) {
			resp.setContentType("text/plain");
		} else if (fileExt.equals("pdf")) {
			resp.setContentType("application/pdf");
		}
		OutputStream os = resp.getOutputStream();
		os.write(art.getFile());
		os.close();
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

}
